package com.kate.aop.proxy;

import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;
public class SampleClass {
    public void test(){
        System.out.println("hello world");
    }
    public static void main(String[] args) {
        //1.目标对象

        //2.黑客对象
        CGLibHk cgLibHk = new CGLibHk();
        Enhancer enhancer = cgLibHk.instance(SampleClass.class);
        //3.代理
        SampleClass sample = (SampleClass) enhancer.create();
        sample.test();
    }
}

class CGLibHk implements  MethodInterceptor{
    public Enhancer instance(Class targetClass){
        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(targetClass);
        enhancer.setCallback(this);
        return enhancer;
    }
    @Override
    public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy)
            throws Throwable {
        System.out.println("开始入侵");
        Object result = proxy.invokeSuper(obj, args);
        System.out.println("结束入侵");
        return result;
    }
}
